package team18.yuejian.Activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import team18.yuejian.Model.MineModel;
import team18.yuejian.R;
import team18.yuejian.RetrofitListener;
import team18.yuejian.bean.UserBean;


public class MineEditActivity extends BaseActivity implements View.OnClickListener,RetrofitListener<UserBean> {

    private EditText username,password,phone,birthday;
    private ImageView userpic,back;
    private DatePicker birthdayModel;
    private RadioGroup gender;
    private Button picButton,makeSure;
    private String sexText;
    private int ugender;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_edit);

        initView();
        initEvent();
    }

    public void initView(){
        username = findViewById(R.id.mine_edit_user);
        password = findViewById(R.id.mine_edit_password);
        userpic = findViewById(R.id.mine_edit_pic);
        gender = findViewById(R.id.mine_edit_sex);
        birthday = findViewById(R.id.mine_edit_birthday);
        phone = findViewById(R.id.mine_edit_phone);

        birthdayModel = findViewById(R.id.birthday_model);

        picButton = findViewById(R.id.mine_edit_birthday_bt);
        makeSure = findViewById(R.id.mine_edit_edit_bt);
        back = findViewById(R.id.mine_edit_back);
    }

    public void initEvent(){
        picButton.setOnClickListener(this);
        makeSure.setOnClickListener(this);
        back.setOnClickListener(this);
        userpic.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.mine_edit_back:
                Toast.makeText(MineEditActivity.this,"返回",Toast.LENGTH_SHORT).show();
                break;

            case R.id.mine_edit_edit_bt:
                Toast.makeText(MineEditActivity.this,"修改",Toast.LENGTH_SHORT).show();
                /*File file = new File("Mine_Logo.png");*/
                if(PNG_Image.exists()){
                    Toast.makeText(MineEditActivity.this,"文件存在",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MineEditActivity.this,"文件不存在",Toast.LENGTH_SHORT).show();
                }
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),PNG_Image);
                MultipartBody.Part body = MultipartBody.Part.createFormData("upic", PNG_Image.getName(), requestBody);
                int uid = getUserId();
                selectRadioButton();
                if ("男".equals(sexText)){
                    ugender = 1;
                }else{
                    ugender = 0;
                }

                RequestBody unameBody = RequestBody.create(MediaType.parse("multipart/form-data"), username.getText().toString().trim());
                RequestBody uidBody = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(uid));
                RequestBody passwordBody = RequestBody.create(MediaType.parse("multipart/form-data"),password.getText().toString().trim());
                RequestBody genderBody = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(ugender));
                RequestBody phoneBody = RequestBody.create(MediaType.parse("multipart/form-data"),phone.getText().toString().trim());
                RequestBody birthdateBody = RequestBody.create(MediaType.parse("multipart/form-data"),birthday.getText().toString().trim());

                Map<String, RequestBody> map = new HashMap<>();

                map.put("uid",uidBody);
                map.put("uname",unameBody);
                map.put("upassword",passwordBody);
                map.put("uphone",phoneBody);
                map.put("ugender",genderBody);
                map.put("ubirthdate",birthdateBody);
                /*Date date = StrToDate(birthday.getText().toString().trim());*/
                MineModel mineModel = new MineModel();
                mineModel.MineEdit(map,body,this);

                Intent intent = new Intent(MineEditActivity.this,MineActivity.class);
                startActivity(intent);


                break;

            case R.id.mine_edit_birthday_bt:
                Toast.makeText(MineEditActivity.this,"生日",Toast.LENGTH_SHORT).show();
                setTime();
                break;

            case R.id.mine_edit_pic:
                Toast.makeText(MineEditActivity.this,"头像",Toast.LENGTH_SHORT).show();
                if (ContextCompat.checkSelfPermission(MineEditActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MineEditActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                } else {
                    openAlbum();
                }
                break;
        }
    }

    @Override
    public void onSuccess(UserBean userBean, int flag) {
            if ("3".equals(userBean.getStatus())){
                Toast.makeText(MineEditActivity.this,userBean.getMsg(),Toast.LENGTH_SHORT).show();
            } else{
                Toast.makeText(MineEditActivity.this,userBean.getMsg(),Toast.LENGTH_SHORT).show();
            }
    }

    @Override
    public void onFail(String msg) {
            Toast.makeText(MineEditActivity.this,msg,Toast.LENGTH_SHORT).show();
    }


    public void setTime(){
        AlertDialog.Builder localBuilder = new AlertDialog.Builder(MineEditActivity.this);
        localBuilder.setTitle("请选择时间");

        final LinearLayout layout_alert = (LinearLayout) getLayoutInflater().inflate(R.layout.time_set_model,null);
        localBuilder.setView(layout_alert);
        localBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
            {
                DatePicker datepicker1= layout_alert.findViewById(R.id.birthday_model);
                int y=datepicker1.getYear();
                int m=datepicker1.getMonth()+1;
                int d=datepicker1.getDayOfMonth();

                birthday.setText(y+"-"+m+"-"+d);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
            {

            }
        }).create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1 :
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                } else {
                    Toast.makeText(this,"权限不够",Toast.LENGTH_SHORT).show();
                }
                break;

            default: break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        switch (requestCode){
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK){
                    if (Build.VERSION.SDK_INT >= 19){
                        handleImageOnKitkat(data,userpic);
                        getImageByView(userpic);
                    } else {
                        handleImageBeforeKitKat(data,userpic);
                    }
                }
                break;

            default: break;
        }
    }

    public void selectRadioButton(){
        gender = findViewById(R.id.mine_edit_sex);
        RadioButton rb = MineEditActivity.this.findViewById(gender.getCheckedRadioButtonId());
        sexText = rb.getText().toString();
        Log.d("Rediobutton",rb.getText().toString());
    }


}
